from django.shortcuts import render,redirect,reverse
from django.http import HttpResponse
from ..models import Users
from django.contrib.auth.hashers import make_password,check_password
from web.settings import BASE_DIR
import os
from . IndexViews import uploads
# Create your views here.
# 商品添加
def useradd(request):
    return render(request,'myadmin/users/add.html')

# 商品数据库添加
def userinsert(request):
    try:
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')

        # 加密
        data['password'] = make_password(data['password'],None,'pbkdf2_sha256')

        # 头像判断
        myfile = request.FILES.get('pic',None)
        if myfile:
            from . IndexViews import uploads
            data['pic'] = uploads(myfile)
        else:
            data['pic'] = '/static/pics/users.jpg'

        # 新建商品到数据库
        Users.objects.create(**data)

         # 网页跳转到列表页
        return HttpResponse("<script>alert('申 请 成 功');location.href='/myadmin/user/index/'</script>")
    except:
        return HttpResponse("<script>alert('申 请 失 败');location.href='/myadmin/user/add/'</script>")





# 商品列表显示 && 列表页分页也放在这里处理;由于使用的账户永久删除,所以不需要使用Users.objects.exclude(status=2)进行筛选
def userindex(request):
    # 读取数据,排除已经逻辑删除的数据
    users = Users.objects.exclude(status=2)
    # 接受搜索类型和页码号
    types  =request.GET.get('types',None)
    keywords = request.GET.get('keywords',None)
    if types:
    # 判断是否有搜索条件
        if types == 'all':
            from django.db.models import Q
            # 从所有类别中选择关键字，因此需要用每个字段去分别匹配
            users = users.filter(Q(username__contains=keywords)|Q(email__contains=keywords)|Q(phone__contains=keywords)|Q(age__contains=keywords))
        else:
            # 通过拼接字符串达到上上行的效果
            data = {types + '__contains':keywords}
            users = users.filter(**data)
    # 数据分页
    from django.core.paginator import Paginator
    # 实例化分页对象p,每页10个
    p = Paginator(users,10)
    # 当前页码page,如果不存在则返回1
    page = request.GET.get('page',1)
    # 当前页面数据
    userlist = p.page(page)                 #使用paginator使用page方法获取到符合当前页面的数据
    # 获取所有页码列表
    # pages = p.page_range
    # 分配数据
    context = {'users': userlist}

    # 加载模板
    return render(request, 'myadmin/users/index.html', context)


# 商品列表中处理删除操作
def userdel(request,iidd):
    # 删除图片
    # filter相当于SQL中的WHERE，可设置条件过滤结果
    # obj = Users.objects.filter(id=iidd)
    # 获取单个对象
    obj = Users.objects.get(id=iidd)
    path_pic = obj.pic

    # pathall1 = os.path.join(BASE_DIR,path_pic)
    pathall = BASE_DIR + path_pic
    #如果图片是默认图片.,则不执行图片删除操作
    if path_pic != '/static/pics/users.jpg':
        os.remove(pathall)
    else:
        pass

    Users.objects.filter(id=iidd).delete()
    return redirect(reverse('myadmin_user_index'))

# 编辑商品信息
def edit(request,edit_id):
    obj = Users.objects.get(id = edit_id)
    context  ={'info':obj}
    return render(request,'myadmin/users/edit.html',context)

def userupdate(request):
    try:
        # 接受的所有数据
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        # 获取商品对象,更新出去id以外的所有值
        obj = Users.objects.get(id=data['id'])
        obj.username = data['username']
        obj.email = data['email']
        obj.age = data['age']
        obj.phone = data['phone']
        obj.sex = data['sex']
        myfile = request.FILES.get('pic', None)
        # 文件存在
        if myfile:
            # 非默认图片
            if obj.pic != '/static/pics/users.jpg' or pbj.pic == None:
                # 删除
                try:
                    os.remove(BASE_DIR + obj.pic)
                except:
                    pass
                # 更新
            obj.pic = uploads(myfile)
        obj.save()
        return HttpResponse('<script>alert("更新成功");location.href="/myadmin/user/index/"</script>')
    except:
        return HttpResponse('<script>alert("更新失败");location.href="/myadmin/user/edit/' + str(obj.id) + '/"</script>')




























